package ichubelastic

import (
	"gitee.com/ichub/webcli/common/base/baseconfig"
	"github.com/olivere/elastic"
	"github.com/sirupsen/logrus"
	"log"
	"os"
	"time"
)

/*
	@Title    文件名称: elastic_search.go
	@Description  描述:  配置文件

	@Author  作者: leijianming@163.com  时间(2024-02-22 22:38:21)
	@Update  作者: leijianming@163.com  时间(2024-02-21 22:38:21)
*/

type ElasticClient struct {
	ClientDto *baseconfig.ElasticClientDto
	client    *elastic.Client `json:"-"`
}

func (this *ElasticClient) Client() *elastic.Client {
	return this.client
}

func (this *ElasticClient) SetClient(client *elastic.Client) {
	this.client = client
}

func NewElasticClient() *ElasticClient {
	return &ElasticClient{}
}
func New(dto *baseconfig.ElasticClientDto) *ElasticClient {
	return &ElasticClient{
		ClientDto: dto,
	}
}

func (this *ElasticClient) Open() (*elastic.Client, error) {
	// 创建ES client用于后续操作ES
	client, err := elastic.NewClient(
		// 设置ES服务地址，支持多个地址
		elastic.SetURL(this.ClientDto.URL),
		// 设置基于http base auth验证的账号和密码
		elastic.SetBasicAuth(this.ClientDto.Username, this.ClientDto.Password),
		// 启用gzip压缩
		elastic.SetGzip(this.ClientDto.Gzip),
		// 设置监控检查时间间隔
		elastic.SetHealthcheckInterval(10*time.Second),
		// 设置请求失败最大重试次数
		elastic.SetMaxRetries(5),
		// 设置错误日志输出
		elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
		// 设置info日志输出
		elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)))
	if err != nil {
		// Handle error
		logrus.Errorf("连接失败: %v\n", err)
	} else {
		logrus.Info("连接成功")
	}
	logrus.Info(client)
	this.client = client
	return client, err
}
func (this *ElasticClient) Close() {

}
